"""
-*- coding: utf-8 -*-
@Time : 2022/5/18 14:58
@Author : XGT-Python
"""
import requests
from lxml import etree
from config import logging


class WebRequest:
    '''
    专门发送请求使用
    '''

    def __init__(self):
        self.resp = None
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Mobile Safari/537.36'}

    def do_get(self, url, headers=None, *args, **kwargs):
        ''' get请求
        headers若传递了就使用headers
        若没传递就使用默认的headaers
        '''
        try:
            if not headers:
                headers = self.headers
            resp = requests.get(url, headers=headers, *args, **kwargs)
            if resp.status_code == 200:
                resp.encoding = 'utf-8'
                self.resp = resp
                return resp

        except Exception as e:
            logging.info(e)

    def do_post(self, url, headers=None, *args, **kwargs):
        try:
            if not headers:
                headers = self.headers
            resp = requests.get(url, headers=headers, *args, **kwargs)
            if resp.status_code == 200:
                resp.encoding = 'utf-8'
                self.resp = resp
                return resp

        except Exception as e:
            logging.info(e)

    def get_tree(self):
        dom = etree.HTML(self.resp.text)
        return dom

    def get_text(self):
        return self.resp.text

    def get_json(self):
        return self.resp.json()

    def get_content(self):
        return self.resp.content
